#!/bin/bash
set -e

DESTDIR="$(pwd)/release"
BASEDIR="$(cd "$(dirname "$0")/.." && pwd)"
APPNAME="$(basename "$BASEDIR")"

cd "$BASEDIR"

if [ -e "$DESTDIR" ]; then
    echo directory \"release\" already exists
    exit 1
fi

echo running tests...

zig build test

echo building...

zig build -Dall_targets --release --prefix "$DESTDIR/build"

VERSION=$(/bin/cat "$DESTDIR/build/version")

git archive --format=tar.gz --output="$DESTDIR/flow-$VERSION-source.tar.gz" HEAD
git archive --format=zip --output="$DESTDIR/flow-$VERSION-source.zip" HEAD

cd "$DESTDIR/build"

TARGETS=$(/bin/ls)

for target in $TARGETS; do
    if [ -d "$target" ]; then
        cd "$target"
        if [ "${target:0:8}" == "windows-" ]; then
            echo packing zip "$target"...
            zip -r "../../${APPNAME}-${VERSION}-${target}.zip" ./*
            cd ..
        else
            echo packing tar "$target"...
            tar -czf "../../${APPNAME}-${VERSION}-${target}.tar.gz" -- *
            cd ..
        fi
    fi
done

cd ..
rm -r build

TARFILES=$(/bin/ls)

for tarfile in $TARFILES; do
    echo signing "$tarfile"...
    gpg --local-user 4E6CF7234FFC4E14531074F98EB1E1BB660E3FB9 --detach-sig "$tarfile"
    sha256sum -b "$tarfile" >"${tarfile}.sha256"
done

echo "done making release $VERSION @ $DESTDIR"
echo

/bin/ls -lah
